package com.qp.basics.estivate;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 忽略key的大小写的Map实现。
 *
 */
public class IgnoreCaseMap<K, V> extends LinkedHashMap<K, V> {
	private Map<String, String> keyMap = new HashMap();

	public IgnoreCaseMap(int initialCapacity, float loadFactor,
			boolean accessOrder) {
		super(initialCapacity, loadFactor, accessOrder);
	}

	public IgnoreCaseMap(int initialCapacity, float loadFactor) {
		super(initialCapacity, loadFactor);
	}

	public IgnoreCaseMap(int initialCapacity) {
		super(initialCapacity);
	}

	public IgnoreCaseMap() {
		super();
	}

	public IgnoreCaseMap(Map<K, V> m) {
		super();
        Iterator<K> it = m.keySet().iterator();
        while (it.hasNext()){
            K key = it.next();
            this.put(key,m.get(key));
        }
	}
	public void putAll(Map<? extends K, ? extends V> m) {
        Iterator<? extends K> it = m.keySet().iterator();
        while (it.hasNext()){
            K key = it.next();
            put(key,m.get(key));
        }
	}
	public V put(K key, V value) {
		if (key instanceof String) {
			String keyStr = (String) key;
			String keyLower = keyStr.toLowerCase();
			String keyx = keyMap.get(keyLower);
			if (keyx == null) {
				keyx = keyStr;
				keyMap.put(keyLower, keyStr);
			}
			key = (K) keyx;
		}
		return super.put(key, value);
	}

	public V get(Object key) {
		if (key instanceof String) {
			String key2 = (String) key;
			key = keyMap.get(key2.toLowerCase());
		}
		return super.get(key);
	}

	public boolean containsKey(Object key) {
		if (key instanceof String) {
			String key2 = (String) key;
			key = keyMap.get(key2.toLowerCase());
		}
		return super.containsKey(key);
	}

	public V remove(Object key) {
		if (key instanceof String) {
			String key2 = (String) key;
			key = keyMap.get(key2.toLowerCase());
		}
		return super.remove(key);
	}
}
